package com.rc.saas.tenant.service.log;

import com.rc.saas.tenant.mongo.TenantOperateLogDao;
import com.rc.saas.tenant.search.tenant.TenantOperateLogSearch;
import com.rc.saas.tenant.vo.log.TenantOperateLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * Created by yang on 2022-05-26
 */
@Service
public class TenantLogServiceImpl implements TenantLogService {
    private static Logger logger = LogManager.getLogger(TenantLogServiceImpl.class);

    @Autowired
    private TenantOperateLogDao tenantOperateLogDao;

    @Override
    public void addTenantOperateLog(TenantOperateLog log) {
        tenantOperateLogDao.insert(log, log.getCollectionName());
        logger.info("addTenantOperateLog mongodb 创建成功,:{},:{}", log.getCollectionName(), log.getUrl());
    }

    @Override
    public PageImpl<TenantOperateLog> findPageTenantOperateLog(TenantOperateLogSearch search) {
        //mongoDB不同，因为mongo中的date类型以UTC（Coordinated Universal Time）存储，就等于GMT（格林尼治标准时）时间,
        //而系统时间使用的是GMT+0800时间，两者正好相差8个小时。也就是用java 代码插入的时间类型的值都会被减8小时,
        //但是查询出来的结果时间还是会被转换回来（不以时间为条件查询的话基本没什么问题）
        //如:2019-11-10T08:36:00Z

        //将ISO 8601 日期格式进行转换
        //DateTimeFormatter isoFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'");
        //DateTimeFormatter dfShort = DateTimeFormat.forPattern("yyyy-MM-dd");
        DateTimeFormatter dfLong = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");

        Query query = new Query();
        if (StringUtils.isNotBlank(search.getTenantCode())) {
            query.addCriteria(Criteria.where("tenantCode").is(search.getTenantCode()));
        }

        if (StringUtils.isNotBlank(search.getTenantOperatorCode())) {
            query.addCriteria(Criteria.where("tenantOperatorCode").is(search.getTenantOperatorCode()));
        }

        if (StringUtils.isNotBlank(search.getStartTime())) {
            DateTime dt = dfLong.parseDateTime(search.getStartTime());

            //如果结束时间为空,就自动加1天,否则mongodb查不出来数据
            if (StringUtils.isBlank(search.getEndTime())) {
                dt = dt.plusDays(1);
                search.setEndTime(dt.toString(dfLong));
            }

            if (StringUtils.isNotBlank(search.getOperator())) {
//                search.setOperator("admin");
                query.addCriteria(Criteria.where("operator").in(search.getOperator()));
            }

            query.addCriteria(
                    new Criteria().andOperator(
                            Criteria.where("createTime").gte(search.getStartTime()),
                            Criteria.where("createTime").lte(search.getEndTime())
                    )
            );

            logger.info("query 查询:{}", query.toString());

            //排序
            Sort sort = Sort.by(Sort.Direction.DESC, "createTime");

            //在开始时间的年月的表中查找
            TenantOperateLog log = new TenantOperateLog(dt.toDate());
            PageImpl<TenantOperateLog> pages = tenantOperateLogDao.findPage(query, sort, search.getOffset(), search.getLimit(), log.getCollectionName());
            return pages;
        } else {
            return null;
        }
    }

}
